package com.rs.adminweb.hospital.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.web.servlet.ModelAndView;

import com.jaxplat.JaxplatBean;
import com.jaxplat.commons.Row;
import com.jaxplat.delegate.CommonsJaxplatDelegate;
import com.rs.commons.delegate.CommonDelegate;
import com.rs.commons.web.AdminBaseAction;
import com.rs.rsbiz.hospital.delegate.HospitalDelegate;
import com.rs.rsbiz.hospital.entity.HospitalEntity;
import com.rs.util.Utils;

public class HospitalAction extends AdminBaseAction
{

    private HospitalDelegate hosDelegate;

    private CommonDelegate commonDelegate;

    public CommonDelegate getCommonDelegate()
    {
        return commonDelegate;
    }

    public void setCommonDelegate(CommonDelegate commonDelegate)
    {
        this.commonDelegate = commonDelegate;
    }

    public HospitalDelegate getHospitalDelegate()
    {
        return hosDelegate;
    }

    public void setHospitalDelegate(HospitalDelegate hosDelegate)
    {
        this.hosDelegate = hosDelegate;
    }

    /**
     * 获取医院信息
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView hosList(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        this.logger.info("初始化医院列表");
        // 为了和portal下的共用dao 重新设置参数名称
        params.put("pageNumber", params.getInt("page") == 0 ? 1 : params.getInt("page"));
        params.put("pageSize", params.getInt("rows") == 0 ? 10 : params.getInt("rows"));
        params.put("pageIndex", params.getInt("pageNumber"));
        // params.put("pageSize", params.getInt("rows"));
        Object[] result = hosDelegate.getHosList(params);
        JSONObject json = new JSONObject();
        json.element("total", (Integer) result[1]);
        json.element("rows", (List) result[0]);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 保存医院信息
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        HospitalEntity entity = (HospitalEntity) this.parseRequestParametersToModel(request, HospitalEntity.class);
        JSONObject json = new JSONObject();
        boolean chkResult = chkUnique(entity, json);
        if (chkResult)
        {
            boolean result = hosDelegate.saveRec(entity);
            if (result)
            {
                json.element("flag", "success");
                json.element("msg", "保存成功!");
            }
            else
            {
                json.element("flag", "fail");
                json.element("msg", "保存失败!");
            }
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 获取医院详情
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        HospitalEntity entity = hosDelegate.getDetailRec(params);
        // JSONObject obj = JSONObject.fromObject(entity);
        // response.setContentType("text/html;charset=UTF-8");
        Map attrs = new HashMap();
        attrs.put("entity", entity);
        // request.setAttribute("entity", entity);
        // response.getWriter().print(obj.toString());
        // response.getWriter().flush();
        // response.getWriter().close();
        return new ModelAndView("../hospital/hospital_view", attrs);
    }

    /**
     * 编辑医院
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        HospitalEntity entity = hosDelegate.getDetailRec(params);
        // 这里用jsonobject.formObject(entity) 在页面调用form('load',..)方法时有问题
        JSONObject obj = new JSONObject();
        obj.element("name", entity.getName());
        obj.element("address", entity.getAddress());
        obj.element("rank_name", entity.getRankName());
        obj.element("route_desc", entity.getRouteDesc());
        obj.element("home_page", entity.getHomePage());
        obj.element("remark", entity.getRemark());
        obj.element("id", entity.getId());
        obj.element("city_code", entity.getCityCode());
        obj.element("path", entity.getPath());
        this.logger.debug(entity.getPath());
        obj.element("self_code", entity.getSelfCode());
        obj.element("remark", entity.getRemark());
        obj.element("fire_flag", entity.getFireFlag());
        // .fromObject(entity);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(obj.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 删除医院信息
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        int result = hosDelegate.deleteRec(params);
        JSONObject json = new JSONObject();
        if (result > 0)
            json.element("msg", "删除成功!");
        else
            json.element("msg", "删除失败!");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 获取城市信息
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView initCity(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        List cityList = hosDelegate.getCityList();
        String rp = request.getParameter("rp");// 请求的页面 查询页面增加所有 编辑页面不需要默认所有
        JSONArray array = JSONArray.fromObject(cityList);
        if (!"e".equals(Utils.checkNullOrBlank(rp)))
        {
            JSONObject obj = new JSONObject();
            obj.put("city_code", "");
            obj.put("city_name", "所有城市");
            obj.put("selected", true);
            array.add(0, obj);
        }else if ("e".equals(rp)){
            JSONObject obj = new JSONObject();
            obj.put("city_code", "530100");
            obj.put("city_name", "昆明");
            obj.put("selected", true);
            array.add(0, obj);
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(array.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 批量导入医院信息 从上传excel文件，再取文件提取信息导入
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView importData(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        params.put("xsdFilePath", request.getRealPath("upload") + "\\xsd\\hospital.xsd");
        StringBuffer sb = new StringBuffer();
        // try{
        JSONArray result = hosDelegate.importData(params);
        // }catch(GeneralException e){
        // sb.append("errMsg:"+e.getMessage());
        // }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(result.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 唯一性校验
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    private boolean chkUnique(HospitalEntity entity, JSONObject obj) throws Exception
    {
        CommonsJaxplatDelegate delegate = (CommonsJaxplatDelegate) JaxplatBean.getBean("commonsJaxplatDelegate");
        String sql = "select count(*) as cnt from t_hospital where name=? ";
        Row tmpRow = null;
        if (Utils.isNullOrBlank(entity.getId()))
        {
            tmpRow = delegate.findRow(sql, new Object[] { entity.getName() });

        }
        else
        {
            sql += " and id <>?";
            tmpRow = delegate.findRow(sql, new Object[] { entity.getName(), entity.getId() });

        }
        if (tmpRow != null && tmpRow.getInt("cnt") > 0)
        {
            obj.put("flag", "fail");
            obj.put("msg", "系统中已存在相同的医院信息!");
            return false;
        }
        else
        {
            return true;
        }
    }
}
